import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data

# 下载mnist数据集
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)

# activation_function=None 无激励函数-->默认是线性函数
def add_layer(inputs, in_size, out_size, activation_function=None):
    # 生成随机矩阵，有in_size行，out_size列
    Weights = tf.Variable(tf.random_normal([in_size,out_size]))
    biases = tf.Variable(tf.zeros([1,out_size]) + 0.1) # Variable推荐初始不为0
    Wx_plus_b = tf.matmul(inputs, Weights) + biases
    if activation_function is None:
        outputs = Wx_plus_b
    else:
        outputs = activation_function(Wx_plus_b)
    return outputs

# 输出准确度
def compute_accuracy(v_xs, v_ys):
global prediction # 全局变量
# y_pre为nx10的向量，每个位置一个0-1的数，表示是该数的几率
y_pre = sess.run(prediction, feed_dict={xs:v_xs}) 
# 对比预测位置是否是真实值的位置，tf.argmax()返回该数组最大值的下标
correct_prediction = tf.equal(tf.argmax(y_pre, 1), tf.argmax(v_ys, 1)) 
# tf.cast()张量类型转换，求出该组数据的正确率
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) 
# 以上仅为定义，该行才开始运算
    result = sess.run(accuracy, feed_dict={xs:v_xs, ys:v_ys}) 
    return result


# 定义 placeholder 对网络进行输入输出
xs = tf.placeholder(tf.float32, [None,784])  # mnist数据集输入为28x28的784个像素点
ys = tf.placeholder(tf.float32, [None,10])   # 输出为一行，表示1-10

# 添加输出层
prediction = add_layer(xs, 784, 10, activation_function=tf.nn.softmax)

# reduction_indices= 0表示行列，1表示按行求
# softmax 和 cross_entropy 搭配，用在分类算法
cross_entropy = tf.reduce_mean(-tf.reduce_sum(ys*tf.log(prediction),reduction_indices=[1]))
# 通过优化器以0.5的效率对误差进行提升
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)

sess = tf.Session()
sess.run(tf.global_variables_initializer()) # 初始化所有变量

for i in range(1000):
# 每次学习100个train数据，保证速度（mini-batch SGD）
    batch_xs, batch_ys = mnist.train.next_batch(100) 
sess.run(train_step,feed_dict={xs:batch_xs, ys:batch_ys})
# 用test数据测试，输出准确度
    if i%50==0:
        print(compute_accuracy(mnist.test.images, mnist.test.labels))